#!/usr/bin/python3
# -*- coding: utf-8 -*-
'通过Appium操作夜神模拟器，浏览App页面'
import random
import sys
import time
from typing import List

from appium import webdriver
from appium.webdriver import WebElement
from appium.webdriver.webdriver import WebDriver

sys.path.append("D:\\workspace\\PycharmProjects\\MySpider\\")

from com.utils.logutil import LogUtil

__author__ = 'Grant Wu'

logger = LogUtil("xiaohongshu", __name__)


class AppOperator:
    def __init__(self):
        self.driverConf = {
            "dviceName": "127.0.0.1:62001",
            "appPackage": "com.xingin.xhs",
            "appActivity": "com.xingin.xhs.activity.SplashActivity",
            "platformName": "android",
            "platformVersion": "7.1.2",
            "noReset": True
        }
        self.driver: WebDriver = None

    def initDriver(self):
        self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", self.driverConf)

    def getSize(self):
        width = self.driver.get_window_size()['width']
        height = self.driver.get_window_size()['height']
        return (width, height)

    def swipeUP(self):
        size = self.getSize()
        x1 = int(size[0] * 0.5)
        y1 = int(size[1] * 0.8)
        y2 = int(size[1] * 0.2)
        self.driver.swipe(x1, y1, x1, y2)

    def swipeDown(self):
        size = self.getSize()
        x1 = int(size[0] * 0.5)
        y1 = int(size[1] * 0.1)
        y2 = int(size[1] * 0.9)
        self.driver.swipe(x1, y1, x1, y2)

    def getElementById(self, id) -> WebElement:
        return self.driver.find_element_by_id(id)


    def getElementsById(self, id) -> List[WebElement]:
        return self.driver.find_elements_by_id(id)

    def getElementByXpath(self,path) -> WebElement:
        return self.driver.find_element_by_xpath(path)

    def serchByKeyWord(self, keyword: str):
        search = app.getElementById("com.xingin.xhs:id/bsc").click(keyword)
        time.sleep(2)
        app.getElementById('com.xingin.xhs:id/ays').send_keys()
        time.sleep(1)
        app.getElementById('com.xingin.xhs:id/ayw').click()
        time.sleep(5)
        swape_count = 1
        tt = True
        while tt == True:
            try:
                finishedElement = app.getElementById('com.xingin.xhs:id/bb_')
                if finishedElement and ('相关比较较少' in finishedElement.text() or 'The End' in finishedElement.text()):
                    tt = False
                logger.warn('======>finished spider data, the end;  page:{}', swape_count)
            except Exception as err:
                logger.info('======>the page has data :{}', swape_count)
                # not  the end of page
                # raise err
            time.sleep(random.randint(3, 10))

            app.swipeUP()
            swape_count += 1
            logger.info('======>go to page : {}', swape_count)

    def browser_homepage(self):
        # downMenu = app.getElementById("com.xingin.xhs:id/mt")
        # time.sleep(1)
        # downMenu.click()
        # time.sleep(2)
        # 这个resourceId可以获取所有频道
        # channels = app.getElementsById("com.xingin.xhs:id/c43")
        channel = app.getElementByXpath(
            '//androidx.appcompat.app.ActionBar.Tab[@content-desc="穿搭"]/android.widget.TextView')
        # for channel in channels:
        #     if '穿搭' in channel.text:
        if channel:
            channel.click()
            time.sleep(3)

            swape_count = 1
            tt = True
            while tt == True:
                try:
                    # finishedElement = app.getElementById('com.xingin.xhs:id/bb_')
                    # if finishedElement and (
                    #         '相关比较较少' in finishedElement.text() or 'The End' in finishedElement.text()):
                    #     tt = False
                    logger.warn('======>finished spider data, the end;  page:{}', swape_count)
                except Exception as err:
                    logger.error('======>the page has data :{}', swape_count)
                    # not  the end of page
                    # raise err
                try:
                    app.swipeUP()
                    time.sleep(random.randint(2, 6))
                except Exception as err:
                    logger.error('======>swipeUP error :{}', swape_count)
                swape_count += 1
                logger.info('======>go to page : {}', swape_count)

    def screen_swape(self):
        swape_count = 1
        tt = True
        while tt == True:
            try:
                finishedElement = app.getElementById('com.xingin.xhs:id/bb_')
                if finishedElement and ('相关比较较少' in finishedElement.text() or 'The End' in finishedElement.text()):
                    tt = False
                logger.warn('======>finished spider data, the end;  page:{}', swape_count)
            except Exception as err:
                logger.error('======>the page has data :{}', swape_count)
                # not  the end of page
                # raise err
            time.sleep(random.randint(3, 10))

            app.swipeUP()
            swape_count += 1
            logger.info('======>go to page : {}', swape_count)


if __name__ == '__main__':
    app = AppOperator()
    app.initDriver()
    size = app.getSize()
    time.sleep(8)

    # app.serchByKeyWord('哪条 哪套 好看')
    app.swipeDown()
    time.sleep(2)
    app.browser_homepage()